package com.jy.api.service.impl;

import com.jy.api.dao.WechatOrderUrlDao;
import com.jy.api.domain.WechatOrderUrl;
import com.jy.api.service.WechatOrderUrlService;
import com.jy.api.signUpReq.WechatUrlReq;
import com.jy.api.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by xiaohua on 2019/4/24.
 */
@Service
public class WechatOrderUrlServiceImpl implements WechatOrderUrlService {
    @Autowired
    private WechatOrderUrlDao urlDao;

    @Override
    public Page<WechatOrderUrl> findAllByStoreId(String storeId, Pageable pageable) {
        return urlDao.findAllByStoreIdOrderByAddTimeDesc(storeId, pageable);
    }

    @Override
    @Transactional
    public Result updateOrSave(WechatUrlReq req) {
        WechatOrderUrl orderUrl;
        if (0 == req.getId()) {
            WechatOrderUrl judgeOrderUrl = urlDao.findByNameAndStoreId(req.getName(), req.getStoreId());
            if (judgeOrderUrl != null) {
                return new Result(400, "该桌号已存在，请核实后进行添加");
            }
            orderUrl = new WechatOrderUrl(req);
        } else {
            WechatOrderUrl judgeOrderUrl = urlDao.findByNameAndStoreId(req.getName(), req.getStoreId());
            if (judgeOrderUrl != null) {
                if (judgeOrderUrl.getId() != req.getId()) {
                    return new Result(400, "该桌号已存在，请核实后进行修改");
                }
            }
            orderUrl = urlDao.findOne(req.getId());
            orderUrl.setName(req.getName());
            orderUrl.setUrl("https://prod-api.huoxingy.com/wechat/member/openid?type=WECHAT-ORDER&storeId=" + req.getStoreId() + "&tableNo=" + req.getTableNo());
        }
        urlDao.save(orderUrl);
        return new Result(200, "添加/保存成功");
    }

    @Override
    @Transactional
    public void deleteById(WechatUrlReq req) {
        WechatOrderUrl orderUrl = urlDao.findOne(req.getId());
        if (null != orderUrl) {
            urlDao.delete(req.getId());
        }
    }
}
